/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


public class AssetLoader implements Runnable {
    private static Thread t;
    private static AssetLoader instance;
    private final List<Runnable> assetQueue = Collections.synchronizedList(new ArrayList<Runnable>(WorldsSettings.MAX_ASSETS));
    private int size = 0;
    public void addItem(Runnable r)
    {
        synchronized(assetQueue)
        {
            assetQueue.add(r);
            size++;
            assetQueue.notify();
        }
    }

    public int[] getInfo()
    {
        return new int[]{size, size - assetQueue.size()};
    }

    public boolean isBusy()
    {
        return !assetQueue.isEmpty();
    }

    public void run() {
        while(true)
        {
            synchronized(assetQueue)
            {
                Iterator<Runnable> itr = assetQueue.iterator();
                while(itr.hasNext())
                {
                    try
                    {
                        itr.next().run();
                    }
                    catch(RuntimeException ex)
                    {
                        Main.log(ex.getMessage());
                        if(Main.debug)
                            ex.printStackTrace();
                    }
                    itr.remove();
                }
                try {
                    assetQueue.wait();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
            size = 0;
        }
    }

    static {
        instance = new AssetLoader();
        t = new Thread(instance);
        t.setName("AssetLoader");
        t.start();
    }
    public static AssetLoader getInstance()
    {
        return instance;
    }
}
